package com.longfor.dragonshard.aspect;

import com.alibaba.fastjson.JSONObject;
import com.longfor.dragonshard.entity.Log;
import com.longfor.dragonshard.service.ILogService;
import com.longfor.drogon.common.bean.LFResultBean;
import com.longfor.drogon.common.util.LFDefaultKeyGenerator;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;

/**
 * @author wangyong
 * @version v1.0
 * @create 2018-01-25 21:30
 **/
@Aspect
@Order(5)
@Component
public class WebLogAspect {
    private Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    private ThreadLocal<Long> startTime = new ThreadLocal<>();
    private ThreadLocal<Log> logThreadLocal = new ThreadLocal<>();

    @Autowired
    private ILogService logService;

    @Pointcut("execution(public * com.longfor.dragonshard.controller.*.add(..)) " +
            "|| execution(public * com.longfor.dragonshard.controller.*.update(..)) " +
            "|| execution(public * com.longfor.dragonshard.controller.*.delete(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String typeFullName = joinPoint.getSignature().getDeclaringTypeName();
        String module = typeFullName.substring(typeFullName.lastIndexOf(".") + 1)
                .replace("Controller", "");
        // 约定第一个参数为DTO或Id
        Object dto = Optional.ofNullable(joinPoint.getArgs())
                .filter(args -> args.length > 0)
                .map(args -> args[0])
                .orElse("");

        Log log = new Log();
        // FIXME POC测试暂时写死，应该取当前登录用户
        log.setUsername("admin");
        log.setOperateTime(new Date());
        log.setType(joinPoint.getSignature().getName());
        log.setModule(module);
        log.setUri(request.getRequestURI());
        log.setParams(dto.toString());
        log.setIp(request.getRemoteAddr());
        LFDefaultKeyGenerator defaultKeyGenerator = new LFDefaultKeyGenerator();
        log.setId(defaultKeyGenerator.generateKey());

        logService.insert(log);

        logThreadLocal.set(log);
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        Log log = logThreadLocal.get();
        // 处理完请求，返回内容
        LFResultBean result = (LFResultBean) ret;
        log.setResponse(JSONObject.toJSONString(result));
        log.setSuccess(result.getCode());
        log.setSpendMillis(System.currentTimeMillis() - startTime.get());
        logService.update(log);

        // 手动回收
        startTime.remove();
        logThreadLocal.remove();
    }
}
